﻿using Sys.Common;
using Sys.Core.Sys;
using Sys.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace Sys.Api
{
    public class PageBase : System.Web.UI.Page
    {
        public SysMenu Menu { get; set; }

        protected override void OnPreInit(EventArgs e)
        {
            string menuid = Context.Request.QueryString["id"];

            if (!string.IsNullOrEmpty(menuid))
            {
                Menu = MenuBll.I.GetByKey(menuid);
            }
        }

        #region 嵌入页面

        /// <summary>
        /// 嵌入样式
        /// </summary>
        /// <param name="file">样式文件</param>
        /// <returns>样式内容</returns>
        public string StyleInclude(string file)
        {
            string physical = HttpContext.Current.Request.PhysicalPath;

            string filepath = physical.Substring(0, physical.LastIndexOf("\\") + 1) + file;

            string styles = string.Empty;

            if (File.Exists(filepath))
            {
                using (StreamReader sr = new StreamReader(filepath))
                {
                    styles = sr.ReadToEnd();
                }
            }

            return "<style type='text/css'>" + styles + "</style>";
        }

        /// <summary>
        /// 潜入脚本
        /// </summary>
        /// <param name="file">脚本文件</param>
        /// <returns>脚本内容</returns>
        public string ScriptInclude(string file)
        {
            string physical = HttpContext.Current.Request.PhysicalPath;

            string filepath = physical.Substring(0, physical.LastIndexOf("\\") + 1) + file;

            string javascript = string.Empty;

            if (File.Exists(filepath))
            {
                using (StreamReader sr = new StreamReader(filepath))
                {
                    javascript = sr.ReadToEnd();
                }
            }

            return "<script type='text/javascript'>" + javascript + "</script>";
        }

        #endregion

        #region 页面工具

        /// <summary>
        /// TabPanel属性
        /// </summary>
        /// <returns>属性HTML内容</returns>
        public string AttrPanel()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(" title='" + Menu.Name + "' fit='true' iconCls='" + Menu.Icon + "'");

            return sb.ToString();
        }

        /// <summary>
        /// 工具栏
        /// </summary>
        /// <returns>工具栏HTML内容</returns>
        public string Toolbar()
        {
            SysUser user = UserBll.CurrentUser;

            if (!user.IsSuper)
            {
                var roles = StringHelper.JoinField(RoleBll.I.EntitiesByUserID(user.ID).Where(m => m.IsVisible).ToList(), "ID");

                var rmbs = RoleMenuButtonBll.I.Entities.Where(m => roles.Contains(m.RoleID) && m.SysMenuButton.SysButton.Type.Equals("Function") && m.SysMenuButton.MenuID.Equals(Menu.ID)).OrderBy(m => m.SysMenuButton.IntSort).ToList();
                var umbs = UserMenuButtonBll.I.Entities.Where(m => m.UserID.Equals(user.ID) && m.SysMenuButton.SysButton.Type.Equals("Function") && m.SysMenuButton.MenuID.Equals(Menu.ID)).OrderBy(m => m.SysMenuButton.IntSort).ToList();

                var list = new List<SysMenuButton>();

                #region 筛选重复

                foreach (var item in umbs)
                {
                    list.Add(item.SysMenuButton);
                }

                foreach (var item in rmbs)
                {
                    bool bit = true;

                    foreach (var temp in list)
                    {
                        if (item.SysMenuButton.ID.Equals(temp.ID))
                        {
                            bit = false; break;
                        }
                    }

                    if (bit) { list.Add(item.SysMenuButton); }
                }

                #endregion

                return ManageButtons(list.OrderBy(m => m.IntSort).ToList());
            }
            else
            {
                return ManageButtons(MenuButtonBll.I.EntitiesByMenuID(Menu.ID).Where(m => m.SysButton.Type.Equals("Function")).ToList());
            }
        }

        /// <summary>
        /// 嵌入页面
        /// </summary>
        /// <param name="tag">页面标记</param>
        /// <returns>结果HTML内容</returns>
        public string Embed(string tag)
        {
            string html = string.Empty;

            SysMenu embed = MenuBll.I.Entities.FirstOrDefault(m => m.Parent.Equals(Menu.ID) && m.Tag.Equals(tag));

            if (embed != null)
            {
                string url = Request.Url.OriginalString.Replace(Menu.ID, embed.ID);

                url = url.Replace(Menu.Tag.ToLower(), embed.Tag.ToLower());

                HttpCookie cookie = Request.Cookies[".ASPXAUTH"];

                CookieContainer cookies = new CookieContainer();

                cookies.Add(new Cookie()
                {
                    Domain = Request.Url.Host,
                    Name = cookie.Name,
                    Expires = cookie.Expires,
                    Path = cookie.Path,
                    Secure = cookie.Secure,
                    Value = cookie.Value
                });

                html = HttpHelper.GetPageHtml(url, cookies);
            }

            return html;
        }

        /// <summary>
        /// 自定义工具栏按钮
        /// </summary>
        /// <param name="icon">图标</param>
        /// <param name="text">文本</param>
        /// <param name="function">方法</param>
        /// <returns>按钮HTML内容</returns>
        public string ToolButton(string icon, string text, string function)
        {
            return "<a href='javascript:void(0)' class='easyui-linkbutton' onclick='" + function + "()' data-options='plain:true,iconCls:\"" + icon + "\"'>" + text + "</a>";
        }

        /// <summary>
        /// 自定义工具栏文本框
        /// </summary>
        /// <param name="id">文本框ID</param>
        /// <returns>文本框HTML内容</returns>
        public string ToolText(string id)
        {
            return "<span style=\"display:inline-block; vertical-align:top; height:22px; padding-top:2px; padding-left:5px;\"><input id=\"" + id + "\" /></span>";
        }

        /// <summary>
        /// 声称按钮
        /// </summary>
        /// <param name="list">实体列表</param>
        /// <returns>按钮HTML内容</returns>
        private string ManageButtons(List<SysMenuButton> list)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var item in list)
            {
                sb.Append(ToolButton(item.SysButton.Icon, item.SysButton.Name, Menu.Tag + "." + item.SysButton.Function));
            }

            return sb.ToString();
        }

        #endregion
    }
}
